package com.example.security1.config.security.user_detail;

import com.example.security1.web.menu.entity.Menu;
import com.example.security1.web.menu.service.MenuService;
import com.example.security1.web.user.entity.User;
import com.example.security1.web.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component("customerUserDetailsService")
@RequiredArgsConstructor
public class CustomerUserDetailsService implements UserDetailsService {

    private final UserService userService;
    private final MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 认证
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 授权
        List<Menu> menuList = menuService.getMenuListByUserId(user.getUId());
        // 去掉为null
        String[] array = menuList
                .stream()
                .filter(Objects::nonNull)
                .map(Menu::getCode)
                .filter(Objects::nonNull)
                .toArray(String[]::new);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
        user.setAuthorities(authorityList);
        user.setPermissionList(menuList);
        return user;
    }
}
